package com.jd.jobkeeper.server.service.db.impl;

import com.jd.jobkeeper.server.configure.ServerConfig;
import com.jd.jobkeeper.server.data.entity.ServerInfo;
import com.jd.jobkeeper.server.data.entity.Status;
import com.jd.jobkeeper.server.data.pesistence.ServerInfoRepository;
import com.jd.jobkeeper.server.service.ServerInfoService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class DBServerInfoServiceImpl implements ServerInfoService {


    final ServerConfig serverConfig;
    final ServerInfoRepository serverInfoRepository;
    ServerInfo serverInfo;

    public DBServerInfoServiceImpl(ServerConfig serverConfig,
                                   ServerInfoRepository serverInfoRepository) {
        this.serverConfig = serverConfig;
        this.serverInfoRepository = serverInfoRepository;
    }


    @Override
    public boolean isSelf(String serverId) {
        return this.serverConfig.getId().equals(serverId);
    }

    @Override
    public boolean isAlive(String serverId) {
        ServerInfo serverInfo = this.serverInfoRepository.findByServerId(serverId);
        if (serverInfo == null) {
            return false;
        }
        return serverInfo.getHeartBeatTime().getTime() > (System.currentTimeMillis() - 150000);
    }

    @Override
    public long getHealthThreshold() {
        return serverConfig.getHeatBeatInterval() * 3;
    }


    @Override
    public ServerInfo currentServer() {
        return this.serverInfo;
    }

    @Override
    public List<ServerInfo> findAll() {
        return serverInfoRepository.findAll();
    }

    @Override
    public void register() {
        serverInfo = serverInfoRepository.findByServerId(serverConfig.getId());
        if (serverInfo == null) {
            serverInfo = new ServerInfo();
            serverInfo.setServerId(this.serverConfig.getId());
            serverInfo.setHost(this.serverConfig.getHost());
            serverInfo.setPort(this.serverConfig.getPort());
            serverInfo.setStatus(Status.ENABLE.getV());
            serverInfo.setCreateTime(new Date());
        }
        heartBeat();
    }

    @Override
    public void unregister() {
        if (this.serverInfo.getId() != null) {
            this.serverInfoRepository.deleteById(this.serverInfo.getId());
        }
    }

    @Override
    public void heartBeat() {
        this.serverInfo.setHeartBeatTime(new Date());
        this.serverInfoRepository.saveAndFlush(serverInfo);
    }
}
